<template>
	<ex-dialog v-model="visible" draggable title="导入图片" :width="600" :contentHeight="215" :top="160">
		<template #default>
			<el-progress v-if="loading" :text-inside="true" :stroke-width="20" :percentage="percentage"/>
			<div v-loading="loading">
				<el-upload
					drag
					class="upload-demo" ref="upload" accept=".zip"
					action=""
					:on-change="save"
					:show-file-list="false"
					:auto-upload="false"
					>
					<slot name="uploader">
						<el-icon class="el-icon--upload"><el-icon-upload-filled /></el-icon>
						<div class="el-upload__text">
							将文件拖到此处或 <em>点击选择文件上传</em>
						</div>
					</slot>
					<template #tip>
						<div class="el-upload__tip">
							<template v-if="tip">{{tip}}</template>
							<template v-else>请上传小于或等于 {{maxSize}}M 的 {{accept}} 格式文件</template>
							<el-link @click="downloadTemplate" target="_blank" type="primary" :underline="false">下载导入模板</el-link>
						</div>
					</template>
				</el-upload>
				<el-form v-if="$slots.form" inline label-width="100px" label-position="left" style="margin-top: 18px;">
					<slot name="form" :formData="formData"></slot>
				</el-form>
			</div>
		</template>
	</ex-dialog>
</template>

<script>
import * as xlsx from "xlsx";
import globalparam from "@/constant/model/globalparam";
import exDialog from '@/components/exDialog'
import facePowder from "@icon-park/vue-next/lib/icons/FacePowder";
import validare from "@/utils/verificate";

export default {
	name:"importImage",
	computed: {},
	emits: ['success'],
	components: {
		exDialog
	},
	props: {
		menu: {
			type: Object, default: () => {
			}
		},
		accept: { type: String, default: ".zip" },
		maxSize: { type: Number, default: 100 },
		tip: { type: String, default: "" },
	},
	data() {
		return {
			visible: false,
			form: {},
			loading: false,
			importAssets:[],
		}
	},
	watch: {},
	mounted() {

	},
	onLoad() {
	},
	methods: {
		//显示
		open(entity) {
			this.importAssets=[];
			this.form = Object.assign({}, entity);
			this.oldForm = Object.assign({}, this.form);
			this.visible = true;
		},
		async close(){
      		this.visible = false;
    	},
		//保存
		async save(file) {
			const files = { 0: file.raw }// 取到File
			if (files.length <= 0) { // 如果没有文件名
				return false
			} else if (!/\.(zip)$/.test(files[0].name.toLowerCase())) {
				this.$message.error('上传格式不正确，请上传zip格式')
				return false
			} else if(file.name.split(".zip")[0] !== this.form.documentCode){
				this.$message.error('上传文件必须是当前单据的单据编号，请重新上传')
				return false
			}
			try {
				this.loading = true
				let formData = new FormData();
				formData.append('file', files[0]);
				let res = await this.$API.asset.documentDetail.uploadDocumentFile.post(formData,{});
				if(res.code===2000){
				  if(res.data.errorList.length>0){
					this.$message.warning("上传数据："+res.data.importDataSize+" 条, 有效数据："+res.data.validDataSize+" 条, 无效数据"+res.data.errorList.length+" 条,已为您自动下载导入结果.")
					this.downloadImportResult(res.data.errorList);
				  }else{
					this.$message.success("上传数据："+res.data.importDataSize+" 条, 有效数据："+res.data.validDataSize+" 条, 无效数据"+res.data.errorList.length+" 条.")
				  }
				  this.$emit('success');
				}
				this.visible = false;
			}catch (e){
				console.log(e);
			}finally {
				this.loading = false;
			}
		},

		downloadImportResult(data) {
			if(Array.isArray(data)){
				let firstData = data[0];
				let tableHeader = [];
				for (let header in firstData ){
					tableHeader.push(header);
				}
				let tableData = [];
				data.forEach(row=>{
					let rowData = [];
					tableHeader.forEach(header=>{
						let value = row[header]+"";
						if(value.startsWith("0")&&validare.isNumber(value)){
							rowData.push("`"+value);
						}else{
							rowData.push(value);
						}
					});
					tableData.push(rowData);
				});
				// 生成XLS文件内容
				let content = '';
				content += tableHeader.join('\t') + '\n'; // 添加表头
				for (let row of tableData) {
					content += row.join('\t') + '\n'; // 添加数据行
				}
				// 创建Blob对象
				const blob = new Blob([content], { type: 'application/vnd.ms-excel' });
				// 创建下载链接
				const downloadLink = document.createElement('a');
				downloadLink.href = URL.createObjectURL(blob);
				downloadLink.download = '批量导入图片错误信息-'+this.form.documentCode+"-"+this.$TOOL.uuid("")+'.xlsx';
				// 模拟点击下载链接
				downloadLink.click();
				this.$confirm(`导入图片存在失败内容,请点击浏览器右上角[↓]下载失败明细`, '提示', {
					type: 'warning',
				}).then(() => {
					return true
				}).catch(() => {
					return false
				})
			}
		},
		convertBase64ToByteArray(base64String) {
			// 解码 Base64 字符串为原始二进制数据
			const binaryString = atob(base64String);
			// 创建一个 Uint8Array 来保存字节数据
			const byteArray = new Uint8Array(binaryString.length);
			// 将每个字符的代码点保存到 byteArray 中
			for (let i = 0; i < binaryString.length; i++) {
				byteArray[i] = binaryString.charCodeAt(i);
			}
			return byteArray;
		},
		async downloadTemplate() {
			this.loading = true
			let queryParams = {
				id:this.form.documentId,
			};
			let response = await this.$API.asset.documentDetail.getUploadTemplateByQuery.post(queryParams);
			if(response.code===2000 && response.data){
				// 将响应数据转换为字节数组
				let byteArray = this.convertBase64ToByteArray(response.data);

				// 将字节数组转换为 Blob 对象
				let blob = new Blob([byteArray], { type: 'application/octet-stream' });

				// 创建一个 URL 对象
				let url = URL.createObjectURL(blob);

				// 创建一个链接元素
				let a = document.createElement('a');
				a.href = url;
				a.download = this.form.documentCode+'.zip'; // 设置下载的文件名
				// 触发下载
				a.click();
				// 释放 URL 对象
				URL.revokeObjectURL(url);
			}
			this.loading = false
		},
	}
}
</script>

<style scoped>
h2 {
	font-size: 17px;
	color: #3c4a54;
	padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
	color: #fff;
}


::v-deep(.dialogselect .el-dialog__header){
  padding: 0px !important;
  margin-right: 0px;
}
::v-deep(.dialogsearch){
 padding-top: 10px;
}

::v-deep(.dialogsearch .el-form-item--default .el-form-item__label){
  font-size: 13px !important;
}

::v-deep(.dialogsearch .el-form-item--default .el-input__inner,.dialogsearch .el-form-item--default .el-date-editor){
  font-size: 13px !important;

}
::v-deep(.upload-demo){
width:96%;
margin-left: 2%;
margin-top: 10px;
}

</style>
